package models

import (
	"math/rand"
	"strings"
)

type User struct {
	ID       int64  `json:"id"`
	Name     string `json:"name"`
	Password string `json:"password"`
	Token    string `json:"token"`
}

// 查单条用户
func (model *User) Getone(condition User) (data User, err error) {
	err = DB.Model(model).Where("id=?", condition.ID).First(&data).Error
	if err != nil {
		return data, err
	}
	return data, nil
}

// 注册
func (model *User) Insert(entity User) (insertID int64, err error) {
	err = DB.Model(model).Create(&entity).Error
	if err != nil {
		return -1, err
	}
	return entity.ID, nil
}

// 登录
func (model *User) Login(condition User) (data User, err error) {
	err = DB.Model(model).Where("name=? and password=?", condition.Name, condition.Password).First(&data).Error
	if err != nil {
		return data, err
	}

	//生成指定长度token
	letters := "qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0123456789"
	var arr [16]string
	for i := range arr {
		n := rand.Intn(62)
		arr[i] = letters[n : n+1]
	}
	token := strings.Join(arr[:], "")
	data.Token = token

	err = DB.Model(model).Where(condition).Update("token", token).Error
	if err != nil {
		return data, err
	}

	return data, nil
}

// 修改
func (model *User) Update(entity User) (insertID int64, err error) {
	err = DB.Model(model).Save(&entity).Error
	if err != nil {
		return -1, err
	}
	return entity.ID, nil
}
